import csv

def load_data(filename):
    """加载CSV文件数据"""
    data = {}
    try:
        # 尝试用UTF-8编码打开，如果失败则尝试GBK
        try:
            with open(filename, mode='r', encoding='utf-8') as file:
                reader = csv.DictReader(file)
                for row in reader:
                    province = row['地区']
                    data[province] = row
        except UnicodeDecodeError:
            with open(filename, mode='r', encoding='gbk') as file:
                reader = csv.DictReader(file)
                for row in reader:
                    province = row['地区']
                    data[province] = row
    except FileNotFoundError:
        print(f"错误：文件 {filename} 未找到！")
        return None
    except KeyError:
        print("错误：CSV文件中缺少'地区'列！")
        return None
    except Exception as e:
        print(f"读取文件时发生错误：{str(e)}")
        return None
    return data


def query_consumption():
    """查询消费数据"""
    # 加载数据
    data = load_data('xiaofei.csv')
    if data is None:
        return

    print("请输入你要查询的城市和项目以逗号分隔：")
    user_input = input().strip()

    # 处理用户输入，支持多种分隔符
    separators = [',', '，', '、', ' ', '_', ';']  # 支持多种分隔符
    for sep in separators:
        if sep in user_input:
            parts = [p.strip() for p in user_input.split(sep) if p.strip()]
            break
    else:
        parts = [user_input]  # 如果没有分隔符，整个作为省份

    if not parts:
        print("错误：输入不能为空！")
        return

    province = parts[0]
    items = parts[1:] if len(parts) > 1 else []

    print(f"你查询的省份是：{province}")

    if province not in data:
        print(f"未找到省份: {province}")
        return

    # 如果没有指定项目，显示所有项目
    if not items:
        print("未指定查询项目，将显示所有消费数据：")
        for item, value in data[province].items():
            if item != '地区':
                print(f"{item}的消费金额为: {value}")
        return

    # 查询指定项目
    for item in items:
        if item in data[province]:
            print(f"{item}的消费金额为: {data[province][item]}")
        else:
            print(f"未找到项目: {item}")


if __name__ == "__main__":
    query_consumption()